package cn.antblog.IO;

import com.csvreader.CsvWriter;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @author yangjy
 * @version 1.0
 * @description: txt 文件转换为 csv文件
 * @date 2022/4/5 10:24
 */
public class Txt2Csv {


    /**
     * txt 文件转换为 csv文件
     *
     * @param txtFilePath
     * @param csvFilePath
     * @param txtFileReg
     * @param csvFileReg
     * @param csvCharset
     */
    public static void txtToCsv(String txtFilePath, String csvFilePath, String txtFileReg, char csvFileReg, String csvCharset) {
        String readFile = txtFilePath;
        String writeFile = csvFilePath;
        File file = new File(readFile);
        try {
            CsvWriter csvWriter = new CsvWriter(writeFile, csvFileReg, Charset.forName(csvCharset));
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String string = "\"日期\"\u0019\"地市\"\u0019\"区县\"\u0019\"营服大类\"\u0019\"营服\"\u0019\"预警单号\"\u0019\"预警类型\"\u0019\"预警业务\"\u0019\"预警指标\"\u0019\"预警地市维度\"\u0019\"预警日期维度\"\u0019\"预警描述\"\u0019\"预警专题索引\"";
            String[] s1 = string.replace("\"", "").split(txtFileReg);
            csvWriter.writeRecord(s1);
            while ((string = bufferedReader.readLine()) != null) {
                String[] s = string.replace("\"", "").split(txtFileReg);
                csvWriter.writeRecord(s);
            }
            csvWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        char splitFlag = 25;
        //String splitFlag = ",";
        txtToCsv("C:\\Users\\YangJingyi\\Desktop\\VISOYJMXDAY20220405.txt", "C:\\Users\\YangJingyi\\Desktop\\VISOYJMXDAY202204055555.csv",
                String.valueOf(splitFlag), ',', "gb2312");
    }
}
